package com.example.untitled1;

import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;

import kotlinx.coroutines.DelicateCoroutinesApi;
import kotlinx.coroutines.Dispatchers;
import kotlinx.coroutines.GlobalScope;


@SuppressLint("MissingPermission")
class AudioRecorder extends Thread{

    static final int frequency = 16000;
    static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;

    private boolean isRun = true;
    private MicrophoneCallback microphoneCallback;

    public void registerMicrophoneCallback(MicrophoneCallback microphoneCallback) {
        this.microphoneCallback = microphoneCallback;
    }

    public void unRegisterMicrophoneCallback() {
        microphoneCallback = null;
    }

    public void destroyAudioRecorder(){
        isRun = false;
    }

    @Override
    public void run() {
        int recBufSize = AudioRecord.getMinBufferSize(frequency, AudioFormat.CHANNEL_IN_MONO, audioEncoding);
//        int plyBufSize = AudioTrack.getMinBufferSize(frequency, AudioFormat.CHANNEL_OUT_MONO, audioEncoding)*2;
        // 管理Java应用程序的音频资源，以记录来自平台音频输入硬件的音频
        AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency, AudioFormat.CHANNEL_IN_MONO, audioEncoding, recBufSize);
        // 音轨 为Java应用程序管理和播放单个音频资源
        // AudioTrack.MODE_STATIC
//        AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, frequency, AudioFormat.CHANNEL_OUT_MONO, audioEncoding, plyBufSize, AudioTrack.MODE_STREAM);
        byte[] recBuf = new byte[recBufSize];
        //从AudioRecord实例开始录制。
        audioRecord.startRecording();
        //开始播放音轨。
//        audioTrack.play();
        while(isRun){
//            try {
                int readLen = audioRecord.read(recBuf, 0, recBufSize);
//                audioTrack.write(recBuf, 0, readLen);
                microphoneCallback.audioData(recBuf);
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
//        audioTrack.stop();
        audioRecord.stop();
        isRun = true;
    }

    interface MicrophoneCallback{
        void audioData(byte[] data);
    }

}